<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script>
</head>
<body>
  <form id="form_login">
    用户名：<input type="text" name="username"> 
    密码：<input type="password" name="password">
    <input type="submit" value="登录">
  </form>

  <div id="content" style="display: none;">
    欢迎您,<span id="user_info"></span><br>
    <div id="form_add" style="padding: 1rem 0;">
      姓名：<input type="text" name="username">
      性别：<input type="text" name="gender">
      民族：<input type="text" name="nation"> 
      身份：<input type="text" name="politicsStatus"> 
      联系方式：<input type="text" name="telephone"> 
      地址：<input type="text" name="address"> 
      <input type="submit" onclick="addHandler()" value="新增">
    </div>
    <table border="1" cellspacing="0" cellpadding="20">
      <thead>
        <tr>
          <th>编号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>民族</th>
          <th>身份</th>
          <th>联系方式</th>
          <th>地址</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        
      </tbody>
    </table>
  </div>
  <script>
    var token;
    var user;
    var id;
    var form = document.querySelector("#form_login");
    var content = document.querySelector("#content");
    var user_info = document.querySelector("#user_info")
    form.onsubmit = function(event){
      // 用xhr对象把http请求发送给服务器端
      // 初始化xhr对象
      var xhr = new XMLHttpRequest();
      // 设置请求行
      xhr.open("POST","http://39.96.21.48:7788/user/login")
      // 请求头
      xhr.setRequestHeader("Content-Type","application/json;charset=utf-8")
      // 请求体（参数）
      var username = document.querySelector("#form_login input[name=username]").value;
      var password = document.querySelector("#form_login input[name=password]").value;
      var data = {
        username:username,
        password:password
      }
      xhr.send(JSON.stringify(data))  // json / qs
      // 监听响应
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            var resp = JSON.parse(xhr.response);
            // console.log(resp);
            if(resp.status === 200){
              token = resp.data.token;
              // 登录成功后，用token换取用户信息
              getInfo();
              // 获取所有用户信息
              userFindAll();
              form.style.display="none";
              content.style.display="block";
            } else {
              alert(resp.message);
            }
          }
        }
      }


      // 阻止表单的同步提交
      event.preventDefault();
    }
    //  获取用户信息
    function getInfo(){
      var xhr = new XMLHttpRequest();
      xhr.open("GET","http://39.96.21.48:7788/user/info?token="+token)
      xhr.setRequestHeader("Authorization",token);
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
      
      // 查询字符串 key=val&key=val
      // json {"key":val, "key":val}
      xhr.send()
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            var resp = JSON.parse(xhr.response)
            user = resp.data;
            user_info.innerText = user.realname;
          }
        }
      }
    }

    // 获取所有用户信息
    function userFindAll() {
      // 初始化ajax对象
      var xhr = new XMLHttpRequest();
      // 创建客户端与服务器端的连接
      xhr.open("GET","http://39.96.21.48:7788/baseUser/findAll")
      xhr.setRequestHeader("Authorization",token);
      // 发送请求
      xhr.send()

      // 设置监听
      xhr.onreadystatechange = function() {
        // console.log(xhr)
        if(xhr.readyState === 4) {
          if(xhr.status === 200) {
            var tr = document.querySelector('tbody tr')
            if(tr){
              var tbody = document.querySelector("tbody")
              tbody.removeChild(tr)
            }
            
            
            var res = JSON.parse(xhr.response)
            content = res.data
            content.forEach(function(item,index,content) {
              // console.log(item)
              var table = document.createElement("table")
              var tr = document.createElement("tr");
              tr.innerHTML = `
                <td><input type="checkbox" name="id" value="`+item.id+`"></td>
                <td>`+item.username+`</td>
                <td>`+item.gender+`</td>
                <td>`+item.nation+`</td>
                <td>`+item.politicsStatus+`</td>
                <td>`+item.telephone+`</td>
                <td>`+item.address+`</td>
                <td>
                  <a href="#" onclick="deleteHandler()" class="btn_delete">删除</a>
                  <a href="#" onclick="editHandler()" class="btn_edit">修改</a>
                </td>`;
              document.getElementsByTagName('tbody')[0].appendChild(tr)
            })
          }
        }
      }

    }
    
    // 添加
    function addHandler() {
      // alert(3)
      // 初始化ajax对象
      var xhr = new XMLHttpRequest();
      // 创建客户端与服务器端的连接
      xhr.open("POST","http://39.96.21.48:7788/baseUser/saveOrUpdate")
      xhr.setRequestHeader("Authorization",token);
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
      // 请求体
      var username = document.querySelector("#form_add input[name=username]").value;
      var gender = document.querySelector("#form_add input[name=gender]").value;
      var nation = document.querySelector("#form_add input[name=nation]").value;
      var politicsStatus = document.querySelector("#form_add input[name=politicsStatus]").value;
      var telephone = document.querySelector("#form_add input[name=telephone]").value;
      var address = document.querySelector("#form_add input[name=address]").value;
      if(id) {
        var data = {
          id:id,
          username:username,
          gender:gender,
          nation:nation,
          politicsStatus:politicsStatus,
          telephone:telephone,
          address:address
        }
      }else {
        var data = {
          username:username,
          gender:gender,
          nation:nation,
          politicsStatus:politicsStatus,
          telephone:telephone,
          address:address
        }
      }
      
      console.log(data)
      // 发送请求
      xhr.send(Qs.stringify(data))

      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
          if(xhr.status === 200) {

            var tr = document.querySelector('tbody tr')
            if(tr){
              var tbody = document.querySelector("tbody")
              tbody.removeChild(tr)
            }

            var table = document.createElement("table")
            var tr = document.createElement("tr");
            tr.innerHTML = `
              <td><input type="checkbox" name="id" value="`+data.id+`"></td>
              <td>`+data.username+`</td>
              <td>`+data.gender+`</td>
              <td>`+data.nation+`</td>
              <td>`+data.politicsStatus+`</td>
              <td>`+data.telephone+`</td>
              <td>`+data.address+`</td>
              <td>
                <a href="#" onclick="deleteHandler()" class="btn_delete">删除</a>
                <a href="#" onclick="editHandler()" class="btn_edit">修改</a>
              </td>`;
            document.getElementsByTagName('tbody')[0].appendChild(tr)
          }
        }
      }
    }

    // 修改
    function editHandler() {
      id = event.target.parentElement.parentElement.children[0].firstElementChild.value
      document.querySelector("#form_add input[name=username]").value = event.target.parentElement.parentElement.children[1].innerText
      document.querySelector("#form_add input[name=gender]").value = event.target.parentElement.parentElement.children[2].innerText
      document.querySelector("#form_add input[name=nation]").value = event.target.parentElement.parentElement.children[3].innerText
      document.querySelector("#form_add input[name=politicsStatus]").value = event.target.parentElement.parentElement.children[4].innerText
      document.querySelector("#form_add input[name=telephone]").value = event.target.parentElement.parentElement.children[5].innerText
      document.querySelector("#form_add input[name=address]").value = event.target.parentElement.parentElement.children[6].innerText
    }

    // 删除
    function deleteHandler() {
      var id = event.target.parentElement.parentElement.firstElementChild.firstElementChild.value
      console.log(id)
      // alert(1)
      var xhr = new XMLHttpRequest();
      // 创建客户端与服务器端的连接
      xhr.open("GET","http://39.96.21.48:7788/baseUser/deleteById?id="+id)
      xhr.setRequestHeader("Authorization",token);
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
      xhr.send()

      // 监听响应
      xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
          if(xhr.status === 200) {
            var res = JSON.parse(xhr.response)
            console.log(res.message)
          }
        }
      }
    }
  </script>
</body>
</html>